<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\admin\logic;

use app\admin\model\Admin;
use app\admin\service\Auth;
use app\common\logic\BaseLogic;
use app\common\service\Token;
use think\db\exception\DbException;

/**
 * 登录逻辑
 * Class LoginLogic
 * @package app\admin\logic
 */
class LoginLogic extends BaseLogic
{
    protected Admin $model;

    protected Token $token;

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->model = new Admin();
        $this->token = new Token();
    }

    /**
     * 登录
     *
     * @param $params
     * @return array
     */
    public function login($params)
    {
        $time = time();
        $admin = $this->model->where('username', '=', $params['username'])->find();

        //用户表登录信息更新
        $admin->login_time = $time;
        $admin->login_ip = request()->ip();
        $admin->save();

        //设置token
        $token = $this->token->setToken($admin->id, Token::TYPE_ADMIN);

        //返回登录信息
        return [
            'nickname' => $admin->nickname ? $admin->nickname : $admin->username,
            'avatar' => $admin->avatar,
            'token' => $token,
        ];
    }

    /**
     * 退出登录
     * @param $token
     * @return bool
     */
    public function logout($token): bool
    {
        //token不存在，不注销
        if (!isset($token)) {
            return false;
        }
        //设置token过期
        return $this->token->expireToken($token, Token::TYPE_ADMIN);
    }

    /**
     * 获取用户信息
     * @param $params
     * @return array
     */
    public function getInfo($params): array
    {
        try {
            $admin = $this->model->find($params['id']);
            $admin->hidden(['password']);
        } catch (DbException $e) {
            $this->throw($e->getMessage());
        }
        $menu = new MenuLogic();
        $data['user'] = $admin->toArray();
        if ($admin->id == env('admin.super_admin')) {
            $data['roles'] = ['superAdmin'];
            $data['codes'] = ['*'];
            $data['routers'] = $menu->getSuperAdminRouters();
        } else {
            $data['roles'] = Auth::getRoleCode();
            $data['codes'] = Auth::getRules();
            $data['routers'] = $menu->getMenuById(Auth::getRulesIds());
        }
        return $data;
    }
}